package com.exit66.jukebox.servlet.xml;

import javax.servlet.http.HttpServletRequest;

import com.exit66.jukebox.Options;
import com.exit66.jukebox.data.Track;
import com.exit66.jukebox.data.TrackCollection;
import com.exit66.jukebox.util.XmlSegment;

public class TrackListServlet extends XmlResponseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4591780114304670440L;

	protected void buildXml(HttpServletRequest req, XmlSegment xml) {
        TrackCollection list = null;
        Track track = null;
		String[] params;
		if (req.getPathInfo() != null)
			params = req.getPathInfo().split("/");
		else
			params = new String[0];
		
        if ((params.length >= 2) && (Options.isInteger(params[1]))) {
            try {
                track = new Track();
                track.setTrackID(new Integer(params[1]).intValue());
                track.fetch();
                
                xml.appendSegment(track.returnXml(true, false));
            }
            catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
        else {
        	list = new TrackCollection();
            int start = 0;
            int count = 0;
            
            if (req.getParameter("start") != null) 
            	start = Integer.parseInt(req.getParameter("start"));
            if (req.getParameter("count") != null) 
            	count = Integer.parseInt(req.getParameter("count"));
            
        	if (params.length > 2) {
                if (params[1].equals("album")) {
                    list.listByAlbum(Integer.parseInt(params[2]), start, count);
                }
                else if (params[1].equals("artist")) {
                    list.listByArtist(Integer.parseInt(params[2]), start, count);
                }
            } else if (params.length > 1) {
                list.list(params[1], start, count);
            }
            
            while (!list.isEOF()) {
                track = (Track)list.getCurrent();
                track.returnXml(true, false, xml);
                list.moveNext();
            }
        }
        
	}

}
